package com.ecoolex.hotel.saas.core.manager;

import com.ecoolex.framework.common.util.Check;
import com.ecoolex.framework.common.util.CollectorUtil;
import com.ecoolex.hotel.saas.core.dao.DepartmentOutletsJointDAO;
import com.ecoolex.hotel.saas.entity.DepartmentOutletsJoint;
import com.ecoolex.hotel.saas.entity.DepartmentOutletsJoint.Column;
import com.ecoolex.hotel.saas.entity.DepartmentOutletsJointExample;
import com.ecoolex.hotel.saas.entity.DepartmentOutletsJointExample.Criteria;

import java.time.Instant;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DepartmentOutletsJointManager {
	
    @Autowired
    private DepartmentOutletsJointDAO dao;
    
    public void update(Integer outletsId, List<Integer> departmentIdList, String updateUser) {
    	List<DepartmentOutletsJoint> oldList = queryByoutletsId(outletsId);
    	departmentIdList.forEach(departmentId -> {
			DepartmentOutletsJoint old = oldList.stream().collect(CollectorUtil.first(o -> o.getDepartmentId().equals(departmentId)));
			if(Check.notNull(old)) {
				oldList.remove(old);
			}else {
				DepartmentOutletsJoint joint = new DepartmentOutletsJoint();
				joint.setOutletsId(outletsId);
				joint.setDepartmentId(departmentId);
				joint.setDeleted(DepartmentOutletsJoint.NOT_DELETED);
				joint.setCreateUser(updateUser);
				joint.setCreateTime(Date.from(Instant.now()));
				joint.setUpdateUser(updateUser);
				joint.setUpdateTime(Date.from(Instant.now()));
				dao.insert(joint);
			}
    	});
    	oldList.forEach(o -> {
    		delete(o, updateUser);
    	});
    }
    
    private List<DepartmentOutletsJoint> queryByoutletsId(Integer outletsId){
    	DepartmentOutletsJointExample example = new DepartmentOutletsJointExample();
    	Criteria criteria = example.createCriteria();
    	criteria.andOutletsIdEqualTo(outletsId).andDeletedEqualTo(DepartmentOutletsJoint.NOT_DELETED);
    	return dao.selectByExample(example);
    }
    
    private void delete(DepartmentOutletsJoint joint, String updateUser) {
    	joint.setDeleted(DepartmentOutletsJoint.IS_DELETED);
    	joint.setUpdateUser(updateUser);
		joint.setUpdateTime(Date.from(Instant.now()));
		dao.updateByPrimaryKeySelective(joint, Column.deleted,Column.updateUser,Column.updateTime);
    }
}